package com.task.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.exception.ApiException;
import com.task.mapper.SysJobMapper;
import com.task.model.SysJobPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author: cxt
 * @time: 2021/11/16
 */
@Service
@Slf4j
public class SysJobService {

    private final SysJobMapper sysJobMapper;

    /**
     * 查询全部可执行任务
     *
     * @param state 状态
     * @return 可执行列表
     */
    public List<SysJobPO> getSysJobAll(Integer state) {
        List<SysJobPO> sysJobAll = sysJobMapper.getSysJobAll(state);
        log.info("查询完成");
        return sysJobAll;
    }

    /**
     * 新增定时任务
     *
     * @param sysJobPO 任务对象
     */
    public void saveJob(SysJobPO sysJobPO) {
        // 检验任务是否重复
        LambdaQueryWrapper<SysJobPO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysJobPO::getBeanName, sysJobPO.getBeanName());
        wrapper.eq(SysJobPO::getMethodName, sysJobPO.getMethodName());
        wrapper.eq(SysJobPO::getCronExpression, sysJobPO.getCronExpression());

        List<SysJobPO> jobPOS = sysJobMapper.selectList(wrapper);
        if (jobPOS.size() != 0) {
            throw new ApiException("任务已经存在");
        }

        // 插入数据库
        sysJobMapper.insert(sysJobPO);
    }

    @Autowired
    public SysJobService(SysJobMapper sysJobMapper) {
        this.sysJobMapper = sysJobMapper;
    }
}
